package com.ddyang.Webflux.controller.flux;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;

import java.time.Duration;
import java.util.Random;

/**
 * @author : daniel.yang
 * @date : 2019/3/11
 * @desc : flux方式的mvc
 * 目的是兼容以往的mvc写法,方便旧项目迁移
 */
@RestController
public class FluxController {

    @GetMapping("/mono")
    public Mono<String> hehe() {

        return Mono.just("hello webFlux!");
    }

    /**
     * 服务端推送: 必须使用Flux<ServerSentEvent<?>>的形式进行返回值设置
     * 标注返回类型为服务端推送
     *
     * @return
     */
    @GetMapping(value = "/flux")
    public Flux<ServerSentEvent<Integer>> flux() {
        return Flux.interval(Duration.ofSeconds(1))
                       .map(data -> new Random().nextInt())
                       .map(data -> ServerSentEvent.<Integer>builder()
                                            .event("random")
                                            .data(data)
                                            .build());

    }
}
